#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct student{
	char* name;
	int average;
}STUDENT; //WHY CAPS?!

void printNames(char **records,int size)
{

   int i;

   printf("The students names are:\n");

   for (i=0 ; i<size ;i++ )

  {

      printf("%s\n" , records[i]);

  }

}

STUDENT *load_students(char *database, int *size)
{
	FILE *fp;
	STUDENT *ret;
	fp = fopen(database, "rb");
	short int len;
	fread(size, sizeof(short int), 1, fp);
	ret = malloc(sizeof(STUDENT) * (*size));
	for(int i=0;i<(*size);i++)
	{
		fread(&len, sizeof(short int), 1, fp);
		ret[i].name = malloc(sizeof(char)*(len+1));
		fread(ret[i].name, sizeof(char), len, fp);
		ret[i].name[len] = '\0';
		fread(&(ret[i].average), sizeof(int), 1, fp);

	}

	return ret;
}
STUDENT **load_sortSorted(char *database, STUDENT *arr, int size)
{
	FILE *fp;
	STUDENT **ret;
	char *indfile;
	int *ind;
	indfile = malloc(sizeof(char)*(strlen(database)+5));
	ret = malloc(sizeof(STUDENT *)*size);
	ind = malloc(sizeof(int)*size);
	sprintf(indfile, "%s.ind", database);
	fp = fopen(indfile, "rb");
	fread(ind, sizeof(int), size, fp);
	for(int i=0;i<size;i++)
		ret[i] = arr + ind[i];

	return ret;
}

char **findAverageGrade(char *database, int avgGrade, int *size)
{
	char **ret = NULL;
	STUDENT *arr, **arr_sort;
	int i;
	int arsize;
	arr = load_students(database, &arsize);
	arr_sort = load_sortSorted(database, arr, arsize);
	i=0;
	while(arr_sort[i]->average < avgGrade) i++;

	ret = malloc(sizeof(char *)*(arsize-1));
	*size = 0;
	while(arr_sort[i]->average==avgGrade)
	{
		ret[*size] = arr_sort[i]->name;
		(*size)++;
		i++;
	}

	return ret;
}

int main(int argc, char** argv)
{

    char **records;

    int resSize = 0;

    records = findAverageGrade(argv[1], 85, &resSize);

    printNames(records,resSize);

    // free memory

	return 1;

}
